package cn.neusoft.tool;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.mysql.cj.util.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Map.class)
public class MapToStringTypeHandler implements TypeHandler<Map<String, String>> {
    private Gson gson = new Gson();

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Map<String, String> stringStringMap, JdbcType jdbcType) throws SQLException {
        String data = gson.toJson(stringStringMap);
        preparedStatement.setString(i, data);
    }

    @Override
    public Map<String, String> getResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);
        if(!StringUtils.isNullOrEmpty(result)){
            return gson.fromJson(result, new TypeToken<Map<String, String>>(){}.getType());
        }
        return null;
    }

    @Override
    public Map<String, String> getResult(ResultSet resultSet, int i) throws SQLException {
        String result = resultSet.getString(i);
        if(!StringUtils.isNullOrEmpty(result)){
            return gson.fromJson(result, new TypeToken<Map<String, String>>(){}.getType());
        }
        return null;
    }

    @Override
    public Map<String, String> getResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        if(!StringUtils.isNullOrEmpty(result)){
            return gson.fromJson(result, new TypeToken<Map<String, String>>(){}.getType());
        }
        return null;
    }
}
